﻿namespace Site2AppWP8
{
    using System;
    using System.IO;
    using System.Linq;
    using System.Net.Http;    
    using System.Text.RegularExpressions;
    using System.Threading.Tasks;
    using System.Xml;
    using Microsoft.Phone.Shell;
    using System.Xml.Linq;
    using System.Collections.Generic;
    using System.Diagnostics;

    /// <summary>
    /// A static class that loads an RSS feed and sets the tile information.
    /// </summary>
    public static class RssTileNotification
    {
        
        /// <summary>
        /// Loads the RSS tile notification.
        /// </summary>
        /// <param name="tilePollFeed">the url to the feed we should pull from</param>
        /// <param name="tileType">type of tile we are using for the app. (0 == flip, 1 == cycle, 2 == iconic) </param>
        /// <param name="showTileImage">Are we showing images on the flip time (Cycle assumes that is all we are showing since that is the point of that tile type, Iconic doesn't show anything except the branding and a badge)</param>
        /// <returns></returns>
        public static async Task LoadRssTileNotification(string tilePollFeed, int tileType, bool showTileImage)
        {
            var shellTile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString() == "/");

            if (shellTile != null)
            {
                
                var httpClient = new HttpClient();               
                
                try
                {
                    switch(tileType)
                    {                        
                        case ((int)WPTileTypes.Flip) :
                            string flipUrl = "http://wat-docs.azurewebsites.net/api/tile/getsingletilexml?feeduri=" + tilePollFeed;

                            if (showTileImage)
                                flipUrl += "&templateStyle=imageandtext";

                            var rssRawData = await httpClient.GetStringAsync(flipUrl);
                            XElement tile  = XElement.Parse(rssRawData);


                            FlipTileData flipTileData = new FlipTileData();

                            foreach(var x in tile.Element("visual").DescendantNodes())
                            {
                                if (x.GetType() == typeof(XElement) && (x as XElement).Name.LocalName == "binding")
                                {
                                    // Don't show Image and square template XML
                                    if (!showTileImage && (x as XElement).Attribute("template").Value == "TileSquare150x150Text04")
                                    {
                                        flipTileData.BackContent = (x as XElement).Element("text").Value;
                                        flipTileData.WideBackContent = (x as XElement).Element("text").Value;
                                    }

                                    // Show image, wide template XML
                                    if (showTileImage && (x as XElement).Attribute("template").Value == "TileWide310x150ImageAndText01")
                                    {                                        
                                        flipTileData.WideBackContent = (x as XElement).Element("text").Value;
                                        flipTileData.WideBackBackgroundImage = new Uri((x as XElement).Element("image").Attribute("src").Value);
                                    }

                                    // Show Image, Square template XML
                                    if (showTileImage && (x as XElement).Attribute("template").Value == "TileSquare310x310ImageAndText01")
                                    {
                                        flipTileData.BackContent = (x as XElement).Element("text").Value;                                        
                                        flipTileData.BackBackgroundImage = new Uri((x as XElement).Element("image").Attribute("src").Value);
                                    }
                                }
                               // FlipTileData properties which can be set

                               //Title = "[title]",
                               //BackTitle = "[back of Tile title]",
                               //BackContent = tile.Element("visual").Element("binding").Element("text").Value,
                               //WideBackContent = tile.Element("visual").Element("binding").Element("text").Value,
                               //Count = [count],
                               //SmallBackgroundImage = [small Tile size URI],
                               //BackgroundImage = [front of medium Tile size URI],
                               //BackBackgroundImage = [back of medium Tile size URI],
                               //WideBackgroundImage = [front of wide Tile size URI],
                               //WideBackBackgroundImage = [back of wide Tile size URI],                                
                            };


                            shellTile.Update(flipTileData);
                            break;

                        case ((int)WPTileTypes.Cycle):
                            
                            string cycleUrl = "http://wat-docs.azurewebsites.net/api/tile/gettilexml?feeduri=" + tilePollFeed;


                            //var rssCycleRawData = await httpClient.GetStringAsync(cycleUrl);
                            //XElement tile  = XElement.Parse(rssRawData);

                            //CycleTileData cycleTileData = new CycleTileData()
                            //{
                            //    Title = "Contoso",
                            //    Count = 10,
                            //    SmallBackgroundImage = new Uri("/Assets/Tiles/smallBackgroundImage.jpg", UriKind.Relative),
                            //    CycleImages = new Uri[5]
                            //};

                            //int iCount = 1;
                            //foreach (XElement element in cycleDoc.Descendants())
                            //{
                            //        // Current API Doesn't return any images
                            //    cycleTileData.CycleImages.Add();
                            //    if(i++ == 10) break;  // only want 5 images to cycle through
                            //}
                            
                            //shellTile.Update(cycleTileData);
                            break;

                        case ((int)WPTileTypes.Iconic):
                            
                            //var rssRawCycleData = await httpClient.GetStringAsync("http://wat-docs.azurewebsites.net/api/tile/getsingletilexml?feeduri=" + tilePollFeed);
                            //XDocument cycleDoc = XDocument.Parse(rssRawData);

                            //IconicTileData iconicTileData = new IconicTileData()
                            //{
                            //   Title = "[title]",
                            //   Count = [count],
                            //   WideContent1 = "[1st row of content]",
                            //   WideContent2 = "[2nd row of content]",
                            //   WideContent3 = "[3rd row of content]",
                            //   SmallIconImage = [small Tile size URI],
                            //   IconImage = [medium/wide Tile size URI],
                            //   BackgroundColor = [.NET color type of Tile]
                            //};

                            //shellTile.Update(iconicTileData);
                            break;
                    }
                }
                catch(Exception ex)
                {
                    // Eat the error and simply don't do an update
                    Debug.WriteLine(ex.Message);
                }
            }
        }

        public enum WPTileTypes { Flip, Cycle, Iconic }
    }
}
